//
//  EighteenViewController.m
//  项目二
//
//  Created by rimi on 16/5/17.
//  Copyright © 2016年 objective. All rights reserved.
//

#import "EighteenViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
@interface EighteenViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>
@property (nonatomic,strong)UISegmentedControl          *segmetedControl;
@property (nonatomic,strong)MKMapView           *mapView;//地图视图

@property (nonatomic,strong)CLLocationManager           *locationManager;
@end

@implementation EighteenViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initializeInterface];
    //定位功能
    if (![CLLocationManager locationServicesEnabled]) {
        
        UIAlertController *alert  = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"当前定位服务不可使用" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    }
    //初始化定位服务
    _locationManager = [[CLLocationManager alloc]init];
    //配置定位精度
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //配置定位过滤
    _locationManager.distanceFilter = 1000;
    
    [_locationManager requestWhenInUseAuthorization];
    //[_locationManager requestAlwaysAuthorization]
    
    
    //设置委托
    _locationManager.delegate = self;
    
    //定位功能非常耗电,使用[_locationManager stopUpdatingLocation]停止定位
    [_locationManager startUpdatingLocation];
    
    //初始化地图
    _mapView = [[MKMapView alloc]initWithFrame:self.view.bounds];
    //是否可以滚动
    _mapView.scrollEnabled = YES;
    //是否可以缩放
    _mapView.zoomEnabled = YES;
    //配置指南针朝向
    [_mapView setUserTrackingMode:MKUserTrackingModeFollowWithHeading];
    //配置地图类型
    _mapView.showsUserLocation = YES;
    _mapView.userLocation.title = @"四川";
    _mapView.userLocation.subtitle = @"四川成都";
    
    _mapView.delegate = self;
    
    [self.view addSubview:_mapView];
    
    //添加长按手势
    UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(respondsToLongGesture:)];
    [self.mapView addGestureRecognizer:longGesture];
}
- (void)initializeInterface {
    self.navigationController.toolbarHidden = NO;
    _segmetedControl = [[UISegmentedControl alloc]initWithItems:@[@"标准",@"卫星",@"混合"]];
    _segmetedControl.selectedSegmentIndex = 0;
    [_segmetedControl addTarget:self action:@selector(typeSegemtedChangeValue:) forControlEvents:UIControlEventValueChanged];
    UIBarButtonItem *segmentItme = [[UIBarButtonItem alloc]initWithCustomView:_segmetedControl];
    UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
//    UIBarButtonItem *locationItem = [[UIBarButtonItem alloc]initWithTitle:@"定位" style:UIBarButtonItemStyleDone target:self action:@selector(locationItemPressed:)];
//    self.navigationItem.leftBarButtonItem = locationItem;
    
    self.toolbarItems = @[flexibleItem,segmentItme,flexibleItem];
}
- (void)typeSegemtedChangeValue:(UISegmentedControl *)sender {
    _mapView.mapType = sender.selectedSegmentIndex;
    
}

//- (void)locationItemPressed:(UIBarButtonItem *)sender {
//    
//}

#pragma mark - <CLLocationManagerDelegate>
//更新位置调用此方法
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations {
    //获取最新的定位
    CLLocation *location = [locations lastObject];
    NSLog(@"纬度= %f,经度 = %f",location.coordinate.latitude,location.coordinate.longitude);
    
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count > 0)
         {
             CLPlacemark *placemark = [array objectAtIndex:0];
             //获取城市
             NSString *city = placemark.locality;
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 city = placemark.administrativeArea;
             }
             NSLog(@"定位完成:%@",city);
             //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
             [manager stopUpdatingLocation];
         }else if (error == nil && [array count] == 0)
         {
             
         }else if (error != nil)
         {
             
         }
     }];
    
    
    
}

#pragma mark - <MKMapViewDelegate>
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    static NSString *identify = @"Pin";
    MKPinAnnotationView *pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identify];
    if (!pinView) {
        pinView = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:identify];
    }
    pinView.pinTintColor = [UIColor blackColor];
    //动画效果
    pinView.animatesDrop = YES;
    //是否弹出弹框
    pinView.canShowCallout = YES;
    
    
    //添加导航按钮
    UIButton *directButton = [UIButton buttonWithType:UIButtonTypeSystem];
    directButton.frame = CGRectMake(0, 0, 80, 30);
    [directButton setTitle:@"导航" forState:UIControlStateNormal];
    pinView.rightCalloutAccessoryView = directButton;
    return pinView;
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    //获取所点击的大头针的标注
    MKPointAnnotation *pointAnnotation = view.annotation;
    //通过标注得到经纬度信息
    CLLocation *location = [[CLLocation alloc]initWithLatitude:pointAnnotation.coordinate.latitude longitude:pointAnnotation.coordinate.longitude];
    //创建逆编码
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *placemark = placemarks[0];
        pointAnnotation.title = placemark.name;
        pointAnnotation.subtitle =placemark.subLocality;
    }];
    
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
    
    MKPlacemark *currentPlacemark = [[MKPlacemark alloc]initWithCoordinate:mapView.userLocation.coordinate addressDictionary:nil];
    MKPlacemark *destinationPlacemark = [[MKPlacemark alloc]initWithCoordinate:((MKPointAnnotation *)view.annotation).coordinate addressDictionary:nil];
    
    //    30.5749386650,104.0649382802
    
    MKMapItem *currentItem = [[MKMapItem alloc]initWithPlacemark:currentPlacemark];
    MKMapItem *destinationItem = [[MKMapItem alloc]initWithPlacemark:destinationPlacemark];
    
    //创建请求
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
    //配置请求
    request.source = currentItem;
    request.destination = destinationItem;
    
    MKDirections *direction = [[MKDirections alloc]initWithRequest:request];
    //发起请求
    [direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"%@",error.description);
        }else {
            [_mapView addOverlay:((MKRoute *)response.routes[0]).polyline];
        }
    }];
    
}

//渲染（画出来）
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
    MKPolylineRenderer *lineRenderer = [[MKPolylineRenderer alloc]initWithPolyline:overlay];
    lineRenderer.lineWidth = 1;
    lineRenderer.strokeColor = [UIColor redColor];
    return lineRenderer;
}

//长按地图添加大头针标注
- (void)respondsToLongGesture:(UILongPressGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        //获取当前点
        CGPoint point = [gesture locationInView:_mapView];
        
        //把点转换为经纬度
        CLLocationCoordinate2D coordinate = [_mapView convertPoint:point toCoordinateFromView:_mapView];
        
        //创建标注
        MKPointAnnotation *pointAnnotation = [[MKPointAnnotation alloc]init];
        
        //配置标注信息
        pointAnnotation.coordinate = coordinate;
        pointAnnotation.title = @"请等待";
        pointAnnotation.subtitle = @"请等待";
        
        //在地图上添加标注
        [_mapView addAnnotation:pointAnnotation];
        
    }
    
    
    
}


@end
